package com.example.a1725185505.works.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.a1725185505.works.R;
import com.example.a1725185505.works.base.URL;
import com.example.a1725185505.works.bean.AllShopBean;
import com.squareup.picasso.Picasso;

import java.util.List;

public class ShopAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<AllShopBean> beans;//向 rv 中填充的数据
    private Context context;//上下文
    private LayoutInflater layoutInflater;//动态布局
    ShopAdapter.OnItemClickListener onItemClickListener;

    public interface OnItemClickListener{
        void onItemClick(View view, int position);
    }
    public void setOnItemClickListener(ShopAdapter.OnItemClickListener listener){
        onItemClickListener= listener;
    }

    public ShopAdapter(Context context)
        {
        this.context=context;
        layoutInflater=LayoutInflater.from(context);
    }
    //自定义 ViewHolder 子类，容纳 item 视图
    public  class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_shop_pic;
        TextView tv_shop_address,tv_shop_shopname;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_shop_pic = itemView.findViewById(R.id.iv_shopall_pic);
            tv_shop_address = itemView.findViewById(R.id.tv_allshop_address);
            tv_shop_shopname = itemView.findViewById(R.id.tv_allshop_shopname);
        }
    }
    //自定义 设置数据 list
    public void setData(List<AllShopBean> beans) {
        this.beans = beans;
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v=layoutInflater.inflate(R.layout.item_allshops,parent,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

        final AllShopBean dataItem = beans.get(position);
        final ViewHolder viewHolder=(ViewHolder)holder;
        Picasso.get().load(URL.BASEUSRL + dataItem.getPic()).
                into(viewHolder.iv_shop_pic);
        viewHolder.tv_shop_shopname.setText(dataItem.getShopname());
        viewHolder.tv_shop_address.setText(dataItem.getAddress());

        if (onItemClickListener!=null){
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickListener.onItemClick(view,position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {  //判断item的个数
        return beans==null?0:beans.size();
    }

}
